﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Icoders.MarketTracker.Core.MasterData;
using Icoders.MarketTracker.Core.Repository.MasterDataRepositories;
using Icoders.MarketTracker.Core.Repository.Transaction;
using Icoders.MarketTracker.Core.Transaction;
using Icoders.MarketTracker.Core.Validation;
using Icoders.MarketTracker.Web.Lib.Model;
using Icoders.MarketTracker.Web.Lib.Security;
using Icoders.MarketTracker.Web.Lib.Services;
using Icoders.MarketTracker.Web.Lib.Util;
using Icoders.MarketTracker.Web.Lib.Validation;

namespace Icoders.MarketTracker.Web.Areas.Mobile.Controllers
{
    [CustomAuthorize(Roles = "ROLE_FSRUSER")]
    public class PurchaseController : Controller
    {
        //
        // GET: /Mobile/Purchase/
        private IPointOfPurchaseRepository _pointOfPurchaseRepository;
        private IClientRepository _clientRepository;
        public IDropDownService _dropDownService;
        private IProductRepository _productRepository;
        private IPurchaseOrderRepository _purchaseOrderRepository;
        private IUserRepository _userRepository;
        private IAuditTrailRepository _auditTrailRepository;

        public PurchaseController(IPointOfPurchaseRepository pointOfPurchaseRepository, IClientRepository clientRepository, IDropDownService dropDownService, IProductRepository productRepository, IPurchaseOrderRepository purchaseOrderRepository, IUserRepository userRepository, IAuditTrailRepository auditTrailRepository)
        {
            _pointOfPurchaseRepository = pointOfPurchaseRepository;
            _clientRepository = clientRepository;
            _dropDownService = dropDownService;
            _productRepository = productRepository;
            _purchaseOrderRepository = purchaseOrderRepository;
            _userRepository = userRepository;
            _auditTrailRepository = auditTrailRepository;
        }

        public ActionResult Index()
        {
            ViewBag.msg = "";
            FsrCustomIdentity identity = (FsrCustomIdentity)User.Identity;
            if (identity != null)
            {
                //var fsrDetails = (FsrUserDetail)Session[SessionConstant.FsrUserDetail];
                if (identity.Area == 0)
                {
                    ViewBag.msg = "Contact your Field Sale Rep Administrator to assign you an area";


                }
                else
                {
                    var pop = new List<PointOfPurchase>();//_pointOfPurchaseRepository.GetByArea(fsrDetails.AreaId);
                    return View(pop);
                }
            }
            else
            {
                ViewBag.msg = "Contact your Field Sale Rep Administrator to assign you an area";
            }
            return View();
        }
        [HttpPost]
        public ActionResult Index(string search)
        {

            ViewBag.msg = "";
            FsrCustomIdentity identity = (FsrCustomIdentity)User.Identity;
            if (identity != null)
            {
                //var fsrDetails = (FsrUserDetail)Session[SessionConstant.FsrUserDetail];
                if (identity.Area == 0)
                {
                    ViewBag.msg = "Contact your Field Sale Rep Administrator to assign you an area";


                }
                else
                {
                    var pop = _pointOfPurchaseRepository.GetBySearch(identity.Area, search);
                    return View(pop);
                }
            }
            {
                ViewBag.msg = "Contact your Field Sale Rep Administrator to assign you an area";
            }
            return View();
        }
        public ActionResult Sell(int popId,bool clear=false)
        {
            try
            {
                PurchaseModel purchase = new PurchaseModel();
                if (clear || Session[SessionConstant.PurchaseDetail] == null)
                {
                   
                   // var fsrDetails = (FsrUserDetail) Session[SessionConstant.FsrUserDetail];
                    FsrCustomIdentity identity = (FsrCustomIdentity)User.Identity;
                    var client = _clientRepository.GetById(identity.Client);
                    var pop = _pointOfPurchaseRepository.GetById(popId);
                    var products = _productRepository.GetByClient(client.Id);
                    purchase.ClientId = client.Id;
                    purchase.ClientName = client.Name;
                    purchase.POPId = pop.Id;
                    purchase.POPName = pop.Name;
                    int id = 1;
                    ViewBag.Popname = purchase.POPName;
                    foreach(var p in  products)
                    {
                        PurchaseItemModel item = new PurchaseItemModel();
                        item.IsPending = true;
                        item.ProductId = p.Id;
                        item.ProductName = p.Name;
                        item.Quantity = 0;
                        item.ReasonId = 0;
                        item.UnitPrice = p.Price;
                        item.Id = id;
                        item.IsSale = false;
                        purchase.Items.Add(item);
                        id++;

                    }
                     Session[SessionConstant.PurchaseDetail] = purchase;
                }
                else
                {
                    purchase = (PurchaseModel) Session[SessionConstant.PurchaseDetail];
                    ViewBag.Popname = purchase.POPName;
                }
                PurchaseItemModel model = purchase.Items.FirstOrDefault(p=>p.IsPending==true);
                if(model==null&&purchase.Items.Count()>0)
                {
                    return RedirectToAction("Finish");
                }
                else if (model == null && purchase.Items.Count() == 0)
                {
                    return View("index");
                }
             return  View("Sell",model);
            }
            catch(Exception ex)
            {
                ValidationSummary.DisplayValidationResult(ex.Message, ModelState);
            }
            return View("index");

        }
        [HttpPost]
        public ActionResult Sell(PurchaseItemModel model)
        {
            PurchaseModel purchase = new PurchaseModel();
            if (model.Quantity < 0)
            {
                ViewBag.IsSell = true;
                purchase = (PurchaseModel)Session[SessionConstant.PurchaseDetail];
                ViewBag.Popname = purchase.POPName;
                ValidationSummary.DisplayValidationResult("Enter valid quantity", ModelState);
                return View(model);
            }
            else if (model.Quantity == 0)
            {
                return RedirectToAction("SellItem", new { itemId = model.Id, isSell=false});
            }
            

            if (Session[SessionConstant.PurchaseDetail] != null)
            {
                purchase = (PurchaseModel)Session[SessionConstant.PurchaseDetail];
                PurchaseItemModel item = purchase.Items.FirstOrDefault(p => p.Id == model.Id);
                item.IsPending = false;
                item.Quantity = model.Quantity;
                item.ReasonId = model.ReasonId;
                Session[SessionConstant.PurchaseDetail] = purchase;
                return RedirectToAction("Sell", new { popId = purchase.POPId });
            }

            return RedirectToAction("Index");
        }

        public ActionResult SellItem(int itemId , bool isSell)
          {
              PurchaseModel purchase = new PurchaseModel();
              PurchaseItemModel model = new PurchaseItemModel();
              ViewBag.IsSell = isSell;
              ViewBag.ReasonList = _dropDownService.GetReason();
              if (Session[SessionConstant.PurchaseDetail] != null)
                {
                    purchase = (PurchaseModel) Session[SessionConstant.PurchaseDetail];
                    model = purchase.Items.FirstOrDefault(p => p.Id == itemId);
                    ViewBag.Popname = purchase.POPName;
                    if (isSell)
                        model.IsSale = true;
                }
              return View(model);
              
          }
          [HttpPost]
          public ActionResult SellItem(PurchaseItemModel model)
          {
              PurchaseModel purchase = new PurchaseModel();
              if(model.IsSale && model.Quantity<=0)
              {
                  ViewBag.IsSell = true;
                  purchase = (PurchaseModel)Session[SessionConstant.PurchaseDetail];
                  ViewBag.Popname = purchase.POPName;
                  ValidationSummary.DisplayValidationResult("Enter valid quantity", ModelState);
                  return View(model);
              }else if(!model.IsSale && model.ReasonId==0)
              {
                  ViewBag.IsSell = false;
                  purchase = (PurchaseModel)Session[SessionConstant.PurchaseDetail];
                  ViewBag.Popname = purchase.POPName;
                  ViewBag.ReasonList = _dropDownService.GetReason();
                  ValidationSummary.DisplayValidationResult("Select Reason", ModelState);
                  return View(model);
              }
              
              if (Session[SessionConstant.PurchaseDetail] != null)
                {
                    purchase = (PurchaseModel) Session[SessionConstant.PurchaseDetail];
                   PurchaseItemModel item = purchase.Items.FirstOrDefault(p => p.Id == model.Id);
                    item.IsPending = false;
                    item.Quantity = model.Quantity;
                    item.ReasonId = model.ReasonId;
                    Session[SessionConstant.PurchaseDetail] = purchase;
                    return RedirectToAction("Sell", new {popId = purchase.POPId});
                }

              return RedirectToAction("Index");
          }
          public ActionResult Finish(PurchaseItemModel model)
          {
              List<PurchaseItemModel> items = new List<PurchaseItemModel>();
              if (Session[SessionConstant.PurchaseDetail] != null)
              {
                PurchaseModel  purchase = (PurchaseModel) Session[SessionConstant.PurchaseDetail];
                ViewBag.Popname = purchase.POPName;
                  items = purchase.Items;
              }
              return View(items);
          }
          [HttpPost]
          public ActionResult Finish()
          {

             try
             {
                 FsrCustomIdentity identity = (FsrCustomIdentity)User.Identity;
                 if (Session[SessionConstant.PurchaseDetail] != null && identity != null)
                {
                   //var fsrDetails = (FsrUserDetail)Session[SessionConstant.FsrUserDetail];
                   PurchaseModel purchase = (PurchaseModel) Session[SessionConstant.PurchaseDetail];
                   PurchaseOrder order = new PurchaseOrder();
                     if(purchase!=null)
                     {
                         order.PopId = purchase.POPId;
                         order.PurchaseOrderRef ="Ord" +DateTime.Now.ToString("yyyyMMddhhmmss");
                         order.ClientId = purchase.ClientId;
                         order.FsrtId = identity.UserID;
                         foreach(var i in purchase.Items)
                         {
                             PurchaseOrderItem item = new PurchaseOrderItem();
                             item.Price = i.UnitPrice;
                             item.Quantity = i.Quantity;
                             item.ReasonId = i.ReasonId;
                             item.ProductId = i.ProductId;
                             order.Items.Add(item);
                         }
                         _purchaseOrderRepository.Save(order);
                         Saveaudit("Added a Purchase", HttpContext.User.Identity.Name, ActionType.Added);
                         Session[SessionConstant.PurchaseDetail] = null;
                     }
                }
                

             }
            catch (DomainValidationException dve)
            {
                ValidationSummary.DisplayDomainValidationResult(dve, ModelState);
                return View();
            }
            catch (Exception ex)
            {
                ValidationSummary.DisplayValidationResult(ex.Message, ModelState);
                return View();
            }
            return RedirectToAction("Index");
          }
          public void Saveaudit(string description, string username, ActionType actionType)
          {
              //  private IUserRepository _userRepository;
              //private IAuditTrailRepository _auditTrailRepository;
              // Saveaudit("Changed Password", HttpContext.User.Identity.Name, ActionType.Updated);
              try
              {
                  User user = _userRepository.GetByUsername(username);
                  AuditTrail auditTrail = new AuditTrail();
                  auditTrail.Description = description;
                  auditTrail.UserId = user.Id;
                  auditTrail.ActionTypeId = Convert.ToInt32(actionType);
                  _auditTrailRepository.Save(auditTrail);
              }
              catch (Exception)
              {
                  throw;
              }
          }
    }
}
